import React from 'react'
import NavBar from '../../components/navBar/navBar.jsx'
import {Form,Field,ErrorMessage,withFormik} from 'formik'
import {Toast} from 'antd-mobile'
import * as Yup from 'yup'
import axios from '../../utils/axios.js'
import './registe.scss'
import {Link} from 'react-router-dom'
 let Registe =(props)=>{
        let {errors,touched}=props
        return <div className='registe'>
            <NavBar>账号注册</NavBar>
            <Form>
                <div className='flex-box'>
                   <label >用户名</label> 
                   <Field className='input' name='username' placeholder='请输入账号'></Field>
                </div >
                <ErrorMessage className='error' name='username' component='div'></ErrorMessage>
                <div className='flex-box'>
                    <label >密   码</label>  
                    <Field className='input' name='password' placeholder='请输入密码'></Field>
                </div >
                <ErrorMessage className='error' name='password' component='div'></ErrorMessage>
                <div className='flex-box'>
                   <label >重复密码</label> 
                   <Field className='input' name='repassword' placeholder='请再次输入密码'></Field>
                </div>
                {errors.repassword&&touched.repassword&&<ErrorMessage className='error' name='repassword' component='div'></ErrorMessage>}
                <button className='btn' type='submit'>注 册</button>
            </Form>
             <div className='foot'>
                 <Link to='/home'>点我回首页</Link>
                 <Link to='/login'>已有账号,去登录</Link>
             </div>
        </div>
}
Registe=withFormik({
    mapPropsToValues:()=>({username:'',password:'',repassword:''}),
    validationSchema:Yup.object().shape({
        username:Yup.string()
                 .required('请输入账号')
                 .matches(/\w{4,8}/,'请输入4到8为字符'),
        password:Yup.string()
                 .required('请输入密码')
                 .matches(/[0-9a-zA-Z]{6}/,'请输入6位数字字母组合'),
        repassword:Yup.string()
                 .required('请再次输入密码')
                 .matches(/[0-9a-zA-Z]{6}/,'请输入6位数字字母组合')

    }),
    validate:(value)=>{
        let error={}
        if(value.repassword!==value.password){
            error.repassword='两次密码输入需要一致'
        }
        return error
         
    },
    handleSubmit:async(values,{props})=>{
        let {username,password}=values
        let res=await axios.post('/user/registered',{
            username,password
        })
        console.log(res,'***--')
        if(res.data.status===200){
            Toast.success('注册成功', 1, null, false);
            setTimeout(()=>{
               props.history.push('/login')
            },1000)
        }else{
            Toast.info('注册失败', 1, null, false);
        }
    }
})(Registe)

export default Registe